<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use App\Models\Authorization;
use App\Transformers\AuthorizationTransformer;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Twilio\Rest\Client;
use Log;

class CodeController extends BaseController
{
	/**
	 * @api {post} /code/pcaptcha 
	 * @apiDescription 发送手机验证码 (send phone captcha code)
	 * @apiGroup Code
	 * @apiPermission jwt
	 * @apiVersion 0.1.0
	 * @apiSuccessExample {json} Success-Response:
	 *     HTTP/1.1 204 No Content
	 */
	public function dxcaptcha(Request $request)
	{
		$validator = \Validator::make($request->input(), [
			'phone' => 'required|regex:/[0-9]{11}/'
		    // 'phone' => 'required|numeric', //|size:11
		]);
		
		if ($validator->fails()) {
		    return $this->returnError($validator);
		}
		
		$phone = $request->get('phone');
		$lang = $request->get('lang');
		$country = $request->get('country');
		$codeSaveSec = 60;
		//create code 
		$code = rand(1000,9999);
		// $code = 1234;
		//save code
		$ret = Cache::put('dx_phone_captcha_'.$country.'_'.$phone, $code, $codeSaveSec);
	
		$accessKeyId = config('api.cn_accessKeyId');
		$accessSecret = config('api.cn_accessSecret');
		$signName = config('api.cn_signName');
		$templateCode = config('api.cn_templateCode');
	
		AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
		                        ->regionId('cn-hangzhou')
		                        ->asDefaultClient();
						
		try {
		    $result = AlibabaCloud::rpc()
		                          ->product('Dysmsapi')
		                          // ->scheme('https') // https | http
		                          ->version('2017-05-25')
		                          ->action('SendSms')
		                          ->method('POST')
		                          ->host('dysmsapi.aliyuncs.com')
		                          ->options([
		                                        'query' => [
		                                          'RegionId' => "cn-hangzhou",
		                                          'PhoneNumbers' => $phone,
		                                          'SignName' => $signName,
		                                          'TemplateCode' => $templateCode,
		                                          'TemplateParam' => "{\"code\":\"".$code."\"}",
		                                        ],
		                                    ])
		                          ->request();
		} catch (ClientException $e) {
			$errorMsg = 'dx code pcaptcha throw '.$e->getErrorMessage();
			Log::info($errorMsg);
			return $this->returnFail($errorMsg);
		} catch (ServerException $e) {
			$errorMsg = 'dx code pcaptcha throw '.$e->getErrorMessage();
			Log::info($errorMsg);
			return $this->returnFail($errorMsg);
		}
		$items = $result->toArray();
	
	    return $this->returnSuccess($items);
	}
	
    /**
     * @api {post} /code/pcaptcha 
     * @apiDescription 发送手机验证码 (send phone captcha code)
     * @apiGroup Code
     * @apiPermission jwt
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 204 No Content
     */
    public function pcaptcha(Request $request)
    {
		$validator = \Validator::make($request->input(), [
			'phone' => 'required|regex:/[0-9]{11}/'
		    // 'phone' => 'required|numeric', //|size:11
		]);
		
		if ($validator->fails()) {
		    return $this->returnError($validator);
		}
		
		$phone = $request->get('phone');
		$lang = $request->get('lang');
		$country = $request->get('country');
		$codeSaveSec = 60;
		//create code 
		$code = rand(1000,9999);
		$code = 1234;
		//save code
		$ret = Cache::put('phone_captcha_'.$country.'_'.$phone, $code, $codeSaveSec);

		$ret = $this->twilio_sms($phone, $country, $lang, $code);
		if($ret === true){
        	    return $this->returnSuccess([]);
		}else{
        	    return $this->returnFail($ret, []);
		}
		$accessKeyId = config('api.cn_accessKeyId');
		$accessSecret = config('api.cn_accessSecret');
		$signName = config('api.cn_signName');
		$templateCode = config('api.cn_templateCode');

		AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
		                        ->regionId('cn-hangzhou')
		                        ->asDefaultClient();
						
		try {
		    $result = AlibabaCloud::rpc()
		                          ->product('Dysmsapi')
		                          // ->scheme('https') // https | http
		                          ->version('2017-05-25')
		                          ->action('SendSms')
		                          ->method('POST')
		                          ->host('dysmsapi.aliyuncs.com')
		                          ->options([
		                                        'query' => [
		                                          'RegionId' => "cn-hangzhou",
		                                          'PhoneNumbers' => $phone,
		                                          'SignName' => $signName,
		                                          'TemplateCode' => $templateCode,
		                                          'TemplateParam' => "{\"code\":\"".$code."\"}",
		                                        ],
		                                    ])
		                          ->request();
		} catch (ClientException $e) {
			$errorMsg = 'code pcaptcha throw '.$e->getErrorMessage();
			Log::info($errorMsg);
			return $this->returnFail($errorMsg);
		} catch (ServerException $e) {
			$errorMsg = 'code pcaptcha throw '.$e->getErrorMessage();
			Log::info($errorMsg);
			return $this->returnFail($errorMsg);
		}
		/*
		{
		        "Message": "OK",
		        "RequestId": "DF850C28-5865-4281-88F0-7A06F4290BBD",
		        "BizId": "183818997018325905^0",
		        "Code": "OK"
		    }
			*/
		$items = $result->toArray();

        return $this->returnSuccess($items);
    }

    /**
     * 发送
     */
    protected function twilio_sms($sendTo, $country, $lang, $code){

	    // Your Account SID and Auth Token from twilio.com/console
	    $account_sid = config('api.twilio_account_sid'); //'AC96f863d668093f9e4f1a52c059344d26';
	    $auth_token = config('api.twilio_auth_token'); //'0fecab99fa76332799353aabd6fb6497';
	    $sms_tpl = config('api.cn_sms_tpl_reglogin');
	    if($lang){
		if($lang == 'en-US'){
		    $sms_tpl = config('api.en_sms_tpl_reglogin');
		}
	    }
	    // In production, these should be environment variables. E.g.:
	    // $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]

	    // A Twilio number you own with SMS capabilities
	    $twilio_number = "+12019044212";
	    $body = str_replace('xxxx', $code, $sms_tpl);
	    $sendTo = $country.$sendTo; 

	    $client = new Client($account_sid, $auth_token);
	    try{
	    	$ret = $client->messages->create(
			    // Where to send a text message (your cell phone?)
			    $sendTo, //'+8615217331661',
			    array(
				    'from' => $twilio_number,
				    'body' => $body, 
				 )
			    );
	    	Log::info($ret);
	    } catch (\Exception $e) {
	        return $e->getMessage();
	    }
	    return true;
    }
}
